from django.contrib.auth.decorators import login_required
from django.contrib.auth import *
from django.contrib.auth import login as django_login
from django.core.handlers.wsgi import *
from django.http import *
from django.shortcuts import *
from .models import *
import logging
import traceback

# 指定所用的logger
logger = logging.getLogger("default_logger")


# Create your views here.
def login(request: WSGIRequest) -> HttpResponse:
    try:
        # 无POST信息和登录失败情况下依旧展示登录页
        resp = render(
            request=request,
            template_name="login.html",
        )
        # 有POST信息时
        if request.POST:
            account = {
                "name": request.POST.get("user_name"),
                "psw": request.POST.get("user_psw"),
            }
            result_data_list = list(query_data(coll="admins_coll", filter=account))
            # 数据库查询账密，有且仅有一条记录为正确情况
            if len(result_data_list) == 1:
                logger.info(u"用户\"%s\"成功登录" % account["name"])
                # 使用django的用户验证
                user = authenticate(
                    request=request,
                    username="admin_00",
                    password="9sU7_r5p:r8eZ8b")
                django_login(request=request, user=user)
                # TODO 用第一种方法，浏览器地址栏的url是不对的
                # resp = index(request=request, user_name=account["name"])

                resp = redirect("http://localhost:" + request.META["SERVER_PORT"] + "/index/" + account["name"] + "/")
        return resp
    except Exception as ex:
        logger.exception(traceback.format_exc())
        return HttpResponseNotFound()


def redirect_to_login(request: WSGIRequest) -> HttpResponse:
    try:
        return login(request)
    except Exception as ex:
        logger.exception(traceback.format_exc())
        return HttpResponseNotFound()


@login_required
def index(request: WSGIRequest, user_name: str) -> HttpResponse:
    try:
        # TODO 未能实现阻止未登录，直接写用户名参数的访问
        print(request.session.keys())
        print(request.session.get(""))
        print(request.user)
        resp = render(
            request=request,
            template_name="index.html",
            context={
                "log_in": True,
                "user_name": user_name
            }
        )
        # 登录失败，重定向回登录页
        return resp
    except Exception as ex:
        logger.exception(traceback.format_exc())
        return HttpResponseNotFound()


@login_required
def insert_info(request: WSGIRequest, user_name: str) -> HttpResponse:
    try:
        # 获取POST里面的数据
        employee_info = {
            "name": request.POST.get(key="name"),
            "id_num": request.POST.get(key="id_num"),
            "sex": request.POST.get(key="sex"),
            "telephone": request.POST.get(key="telephone"),
            "household": request.POST.get(key="household"),
            "home_addr": request.POST.get(key="home_addr"),
            "post": request.POST.get(key="post"),
            "hire_date": request.POST.get(key="hire_date"),
        }
        can_insert = True
        # 检查有无必填项未填写
        for key, value in employee_info.items():
            if value == "" or value is None:
                can_insert = False
                break
        # 所有必填项均填写，将信息插入数据库
        if can_insert:
            insert_data(coll="employee_info_coll", data=employee_info)
            logger.info(u"雇员\"%s\"的信息已成功写入数据库\"%s\"" %
                        (employee_info["name"], "employee_info_coll"))
            # messages.success(request, str(request.POST.get(key="name")) + "的信息已成功录入！")
        return render(
            request=request,
            template_name="insert_info.html",
            context={
                "user_name": user_name
            }
        )
    except Exception as ex:
        logger.exception(traceback.format_exc())
        return HttpResponseNotFound()


@login_required
def query_info(request: WSGIRequest, user_name: str) -> HttpResponse:
    try:
        # 获取POST里面的数据
        employee_filter = {
            "name": request.POST.get(key="query_name"),
        }
        result_data_list = list(query_data(coll="employee_info_coll", filter=employee_filter))
        if len(result_data_list) == 1:
            logger.info(u"成功查询到\"%s\"的信息" % employee_filter["name"])
            result = result_data_list[0]
            result["user_name"] = user_name
            resp = render(
                request=request,
                template_name="query_info.html",
                context=result
            )
        else:
            resp = render(
                request=request,
                template_name="query_info.html",
                context={
                    "user_name": user_name
                }
            )
        return resp
    except Exception as ex:
        logger.exception(traceback.format_exc())
        return HttpResponseNotFound()


@login_required
def update_info(request: WSGIRequest, user_name: str) -> HttpResponse:
    try:
        # TODO 更新数据完全没做好
        employee_filter = {
            "name": request.POST.get(key="name"),
        }
        resp = render(
            request=request,
            template_name="update_info.html",
        )
        if "get" in request.POST:
            result_data_list = list(query_data(coll="employee_info_coll", filter=employee_filter))
            if len(result_data_list) == 1:
                logger.info(u"成功查询到\"%s\"的信息，在更新数据" % employee_filter["name"])
                result = result_data_list[0]
                result["user_name"] = user_name
                resp = render(
                    request=request,
                    template_name="update_info.html",
                    context=result
                )
        elif "submit" in request.POST:
            employee_info = {
                "name": request.POST.get(key="name"),
                "id_num": request.POST.get(key="id_num"),
                "sex": request.POST.get(key="sex"),
                "telephone": request.POST.get(key="telephone"),
                "household": request.POST.get(key="household"),
                "home_addr": request.POST.get(key="home_addr"),
                "post": request.POST.get(key="post"),
                "hire_date": request.POST.get(key="hire_date"),
            }
            # 更新数据
            update_data(coll="employee_info_coll", filter=employee_filter, data=employee_info)
            logger.info(u"成功更新\"%s\"的信息" % employee_filter["name"])

        return resp
    except Exception as ex:
        logger.exception(traceback.format_exc())
        return HttpResponseNotFound()


@login_required
def delete_info(request: WSGIRequest, user_name: str) -> HttpResponse:
    # TODO 第一次访问删除页显示内容错误
    try:
        resp = render(
            request=request,
            template_name="delete_info.html",
            context={
                "user_name": user_name,
                "del_status": 0
            }
        )
        # 获取POST里面的数据
        employee_filter = {
            "name": request.POST.get(key="query_name"),
        }
        has_deleted = delete_data(coll="employee_info_coll", filter=employee_filter)
        if has_deleted:
            logger.info(u"成功删除\"%s\"的信息" % employee_filter["name"])
            resp = render(
                request=request,
                template_name="delete_info.html",
                context={
                    "user_name": user_name,
                    "del_status": 1,
                }
            )
        else:
            logger.info(u"删除\"%s\"失败" % employee_filter["name"])
            resp = render(
                request=request,
                template_name="delete_info.html",
                context={
                    "user_name": user_name,
                    "del_status": 2,
                }
            )
        return resp
    except Exception as ex:
        logger.exception(traceback.format_exc())
        return HttpResponseNotFound()


def error(request: WSGIRequest) -> HttpResponseBadRequest:
    return HttpResponseBadRequest(request=request)
